﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;//treeview的命名空间
using System.Data.SqlClient;//sql语句


namespace community.LanFen
{
    public partial class department : Form
    {
        string currentID;
        string currentName;

        int logo = 0; //0为标志，修改数据,1为添加节点；
        

        public department()
        {
            InitializeComponent();
        }


        protected override bool ProcessDialogKey(Keys keyData)//按enter键时，光标跳到下一个控件输入
        {
            if (keyData == Keys.Enter)//&& !(ActiveControl is Button))
            {//碰到Button时不跳转到下一个控件，而是执行Button的单击事件
                keyData = Keys.Tab;
            }
            return base.ProcessDialogKey(keyData);
        }

        //根据数据库生成节点。
        private void show_nodes()
        {
            SqlConnection con1 = new SqlConnection(SQL.conStr);
            SqlCommand com1 = con1.CreateCommand();
            com1.CommandText = "select DEPTNAME_VCHR ,DEPTID_CHR from T_BSE_DEPARTMENT where PARENTID = '0000000' and STATUS_INT =1";
            //把结果存入结果集
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = com1;
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt1 = ds.Tables[0];
            //创建根节点“全院”
            TreeNode node0 = treeView1.Nodes.Add("全院");//根节点
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                foreach (DataRow dr1 in dt1.Rows)
                {
                    //显示一级节点
                    string id = dr1["DEPTID_CHR"].ToString().Trim();
                    TreeNode tt = new TreeNode();//建立一级节点
                    tt.Text = dr1["DEPTNAME_VCHR"].ToString();
                    node0.Nodes.Add(tt);//将一级节点加入根节点（关键处）
                    //treeView1.SelectedNode = tt;
                    SqlCommand com2 = con1.CreateCommand();
                    com2.CommandText = "select DEPTNAME_VCHR from dbo.T_BSE_DEPARTMENT where PARENTID = @parentID and STATUS_INT =1";
                    com2.Parameters.Add("@parentID", SqlDbType.Char, 15).Value = id;
                    //MessageBox.Show(id );
                    //把结果存入结果集2
                    SqlDataAdapter da2 = new SqlDataAdapter();
                    da2.SelectCommand = com2;
                    DataTable dt_temp = new DataTable("dt_node_c");
                    da2.Fill(dt_temp);
                    foreach (DataRow drt in dt_temp.Rows)
                    {
                        TreeNode ss = new TreeNode();//建立二级节点
                        ss.Text = drt["DEPTNAME_VCHR"].ToString();
                        tt.Nodes.Add(ss);//将二级节点添加到一级节点
                        
                    }
                    treeView1.ExpandAll();
                }
            }
        }

        private void department_Load(object sender, EventArgs e)
        {
            show_nodes();

        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //MessageBox.Show(e.Node.Text);
            string currentText = e.Node.Text;
            string sqlText = "select DEPTID_CHR , DEPTNAME_VCHR,CATEGORY_INT ,INPATIENTOROUTPATIENT_INT, PARENTID,PUTMED_INT ,ATTRIBUTEID,EXPERTDEPTFLAG_INT,STDBED_COUNT_INT ,STATUS_INT ,ADDRESS_VCHR from T_BSE_DEPARTMENT ";
            sqlText += "where DEPTNAME_VCHR = '" + currentText + "'";
            using (SqlConnection con = new SqlConnection(SQL.conStr))
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                SqlCommand com = con.CreateCommand();
                com.CommandText = sqlText;
                SqlDataReader rdr = com.ExecuteReader();

                while (rdr.Read())
                {
                    //保存当前id和name
                    currentID = code_dept.Text = rdr["DEPTID_CHR"].ToString();
                    currentName = name_dept.Text = rdr["DEPTNAME_VCHR"].ToString();

                    kind_box.Text = rdr["CATEGORY_INT"].ToString();
                    attributeID.Text = rdr["INPATIENTOROUTPATIENT_INT"].ToString();

                    //parentNode.Text = rdr["PARENTID"].ToString(); //上级
                    parentNode.Text = getDeptName(rdr["PARENTID"].ToString());
                    putmed.Text = rdr["PUTMED_INT"].ToString();
                    type_dept.Text = rdr["ATTRIBUTEID"].ToString();

                    expert.Text = rdr["EXPERTDEPTFLAG_INT"].ToString ();
                    bed_count.Text = rdr["STDBED_COUNT_INT"].ToString();


                    if (Convert.ToInt32(rdr["STATUS_INT"]) == 1)
                    {
                        status_box.Text = "启用";
                    }else
                        status_box.Text = "不启用";
                    adrr_dept.Text = rdr["ADDRESS_VCHR"].ToString();

                }

            }

        }

        //name取出id
        private string getDeptID(string name)
        {
            using (SqlConnection con = new SqlConnection(SQL.conStr))
            {
                string sqlText = "select DEPTID_CHR , DEPTNAME_VCHR from T_BSE_DEPARTMENT where DEPTNAME_VCHR = '" + name + "'";

                if (con.State == ConnectionState.Closed)
                    con.Open();
                SqlCommand com = con.CreateCommand();
                com.CommandText = sqlText;
                SqlDataReader rdr = com.ExecuteReader();
                string s = "";
                while (rdr.Read())
                {
                    s = rdr["DEPTID_CHR"].ToString();

                }
                return s;
            }
        }
      

        private string getDeptName(string id)
        {
            using (SqlConnection con = new SqlConnection(SQL.conStr))
            {
                string sqlText = "select DEPTID_CHR , DEPTNAME_VCHR from T_BSE_DEPARTMENT where DEPTID_CHR = '" + id + "'";

                if (con.State == ConnectionState.Closed)
                    con.Open();
                SqlCommand com = con.CreateCommand();
                com.CommandText = sqlText;
                SqlDataReader rdr = com.ExecuteReader();
                string s = "";
                while (rdr.Read())
                {
                    s = rdr["DEPTNAME_VCHR"].ToString();

                }
                return s;
            }
        }

        //判断名字是否已经存在
        private bool  judgeName()
        {
            bool deptName_exists = false ;

            SqlConnection con1 = new SqlConnection(SQL.conStr);
            SqlCommand com1 = con1.CreateCommand();
            com1.CommandText = "select DEPTNAME_VCHR ,DEPTID_CHR from T_BSE_DEPARTMENT ";
            //把结果存入结果集
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = com1;
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (name_dept.Text == dr["DEPTNAME_VCHR"].ToString())
                    {
                        deptName_exists = true;
                        MessageBox.Show("该科室名已经存在，请重新填写！");
                        
                    }
                    
                }
            }
            return deptName_exists;
            
        }

        private void save_Click(object sender, EventArgs e)
        {
            //添加子节点
            if (logo==1)
            {
                //判断名字是否已经存在
                if (judgeName() == true)
                {
                    return;
                }

                addNode();

                treeView1.Nodes.Clear();
                show_nodes();
                boxClear();
                parentNode.Enabled = true;
                code_dept.Enabled = true;
                return;
            }

            string stat;
            if (status_box.Text.Trim() == "启用")
            {
                stat = "1";
            }
            else
            {
                stat = "0";
            }
                    


            string sqlText = "update dbo.T_BSE_DEPARTMENT set DEPTID_CHR = '" + code_dept.Text.Trim() + "' , DEPTNAME_VCHR ='" + name_dept.Text.Trim() + "',CATEGORY_INT ='";
            sqlText += kind_box.Text.Trim() + "',INPATIENTOROUTPATIENT_INT ='" + attributeID.Text.Trim() + "', PARENTID = '" + getDeptID(parentNode.Text.Trim()) + "',PUTMED_INT = '" + putmed.Text.Trim() + "',ATTRIBUTEID = '" + type_dept.Text.Trim() + "',EXPERTDEPTFLAG_INT ='" + expert.Text.Trim() + "',STDBED_COUNT_INT = '";
            sqlText += bed_count.Text.Trim() + "',STATUS_INT ='" + stat + "',ADDRESS_VCHR ='" + adrr_dept.Text.Trim() + "' ";
            sqlText += "where DEPTID_CHR = '" + currentID + "'";
            //MessageBox.Show(sqlText );

            using (SqlConnection conn = new SqlConnection(SQL.conStr))
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand com = conn.CreateCommand();
                com.CommandText = sqlText;                

                int ii=0;
                try
                {
                    ii = com.ExecuteNonQuery();
                    if (ii == 1)
                        MessageBox.Show("恭喜！修改成功！");
                    else
                    {

                        MessageBox.Show("修改失败！");
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show("修改异常"+ex.ToString());
                }
            }

            treeView1.Nodes.Clear();
            show_nodes();
        }

        //清空文本框
        private void boxClear()
        {
            code_dept.Text = "自动生成编号";
            code_dept.Enabled = false;
            name_dept.Text = "";
            kind_box.Text = "";
            attributeID.Text = "";
            parentNode.Text = "";
            putmed.Text = "";
            type_dept.Text = "";
            expert.Text = "";
            bed_count.Text = "";
            status_box.Text = "启用";
            adrr_dept.Text = "";

            
            
        }

        //添加子节点方法
        private void addNode()
        {
            //自动生成编号
            sql_database sd = new sql_database ();
            int   autoCode = sd.getSerial("T_BSE_DEPARTMENT", "DEPTID_CHR");

            //MessageBox.Show(autoCode.ToString () );

            string stat;
            if (status_box.Text.Trim() == "启用")
            {
                stat = "1";
            }
            else
            {
                stat = "0";
            }

            string sqlText = "insert into T_BSE_DEPARTMENT (DEPTID_CHR , DEPTNAME_VCHR,CATEGORY_INT ,INPATIENTOROUTPATIENT_INT, PARENTID,PUTMED_INT ,ATTRIBUTEID,EXPERTDEPTFLAG_INT,STDBED_COUNT_INT ,STATUS_INT ,ADDRESS_VCHR) values ('";
            sqlText += autoCode.ToString ()  + "','" + name_dept.Text.Trim() + "','" + kind_box.Text.Trim() + "','" + attributeID.Text.Trim() + "','" + currentID + "','" + putmed.Text.Trim() + "','";
            sqlText += type_dept.Text.Trim() + "','" + expert.Text.Trim() + "','" + bed_count.Text.Trim() + "','" + stat + "','" + adrr_dept.Text.Trim() + "')";

            using (SqlConnection conn = new SqlConnection(SQL.conStr))
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand com = conn.CreateCommand();
                com.CommandText = sqlText;

                int ii = 0;
                try
                {
                    ii = com.ExecuteNonQuery();
                    if (ii == 1)
                        MessageBox.Show("恭喜！添加成功！");
                    else
                    {

                        MessageBox.Show("添加失败！");
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show("添加异常！！！" + ex.ToString());
                }
            }
            logo = 0; //保存标志设置为0
        }

        private void 新增节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            parentNode.Enabled = false;//设置上级部门文本框输入不能使用
            //清空文本框
            boxClear();

            //标志设为1
            logo = 1;            
        }

        private void 删除节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除改记录吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;

            string sqlText = "delete from T_BSE_DEPARTMENT where DEPTID_CHR = '"+currentID + "'";

            using (SqlConnection conn = new SqlConnection(SQL.conStr))
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand com = conn.CreateCommand();
                com.CommandText = sqlText;

                int ii = 0;
                try
                {
                    ii = com.ExecuteNonQuery();
                    if (ii == 1)
                        MessageBox.Show("删除成功！");
                    else
                    {

                        MessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show( ex.ToString());
                }
            }
            //刷新
            treeView1.Nodes.Clear();
            show_nodes();
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            show_nodes();
            boxClear();
        }

        private void parentNode_Click(object sender, EventArgs e)
        {
            dataGridView1.Visible = true;
            try
            {
                SqlConnection cn = new SqlConnection(SQL.conStr);
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                }

                string sqlStr = "select DEPTNAME_VCHR as 科室名称 ,DEPTID_CHR as ID from T_BSE_DEPARTMENT  ";
                SqlDataAdapter dt = new SqlDataAdapter(sqlStr, cn);
                DataSet ds = new DataSet();
                dt.Fill(ds);
                this.dataGridView1.DataSource = ds.Tables[0];
                cn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                parentNode.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
                if (parentNode.Text != null) dataGridView1.Visible = false;
            }
        }



    

    }
}
